import path from "path";
import fs from "fs";
import stream from "stream";
import { promisify } from "util";

// 访问的页面历史
const history = new Map();

const state = {
  retry: [], // 待重试的图片
  failPic: [], // 下载失败的图片
  successNum: 0, // 下载成功的图片数量
  size: 0, // 累计下载大小（kb）
  startTime: +new Date(), // 下载开始时间
};

const pipeline = promisify(stream.pipeline);

// 处理标题，将特殊字符去除
const clean = (name) => name.replace(/[<>:"/\\|?*]/g, "");

// 创建所需目录
function makeDirs(dirname) {
  if (fs.existsSync(dirname)) return true;
  if (makeDirs(path.dirname(dirname))) {
    try {
      fs.mkdirSync(dirname);
      return true;
    } catch (error) {
      console.error("Error creating directory:", error.message);
      return false;
    }
  }
  return true;
}

// 获取url的origin
function getOrigin(url) {
  const urlObj = new URL(url);
  return urlObj.origin;
}

// 显示耗时
function elapsed(startTime) {
  const seconds = Math.floor(+new Date() - startTime);
  const min = Math.floor(seconds / 60000);
  const sec = Math.floor(seconds % 60000) / 1000;
  return `${min}分 ${sec < 10 ? "0" + sec : sec}秒`;
}

// 统计图片大小
async function countSize(filePath) {
  const stats = await fs.promises.stat(filePath);
  const fileSizeInBytes = stats.size;
  const fileSizeInKilobytes = fileSizeInBytes / 1024;
  state.size += Number(fileSizeInKilobytes.toFixed(2));
}

// 监听退出动作（例如 Ctrl+C）
process.on("SIGINT", () => {
  console.log("\n-----------终止运行-----------");
  process.exit(0); // 退出进程
});
// 监听退出进程
process.on("exit", () => {
  const { startTime, successNum, size, retry, failPic } = state;

  console.log("\n-----------下载结束----------\n");

  console.log("访问历史：", history);
  console.log("共耗时:", elapsed(startTime));
  console.log(
    `下载成功：${successNum} ,失败：${retry.length || failPic.length}`,
    retry.length ? retry : failPic
  );
  console.log(
    `平均耗时：${
      !successNum
        ? "0"
        : Math.floor((+new Date() - startTime) / successNum) / 1000
    }秒/张`
  );
  const total = Math.floor((size / 1024) * 100) / 100;
  console.log(`总大小：${total}mb`);
  console.log(
    `下载速度：${
      !size
        ? "0"
        : Math.floor(((total * 1000) / (+new Date() - startTime)) * 100) / 100
    }mb/秒`
  );
  console.log("\n");
});

export { state, history, pipeline, clean, makeDirs, countSize, getOrigin };
